const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const VueLoaderPlugin = require('vue-loader/lib/plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')

const env = process.env.NODE_ENV

if (env === 'production') {
  var outputFilename = '[name]-[contenthash:6].js'
  var imageName = `img/[name]-[contenthash:6].[ext]`
  var cssName = '-[contenthash:6]'
} else {
  var outputFilename = '[name].js'
  var imageName = `img/[name].[ext]`
  var cssName = ''
}

module.exports = {
  // 配置入口
  // entry: './src/index.js'
  // entry: ['./src/index.js', './src/app.js']
  entry: {
    'js/index': './src/index.js'
  },

  // 配置出口
  output: {
    path: path.resolve(__dirname, '../dist'),
    // filename: '[name]-[contenthash:6].js'
    filename: outputFilename
  },

  // resolve 解析选项
  resolve: {
    extensions: ['.js', '.json', '.vue']
  },

  // loader配置
  module: {
    rules: [
      // babel-loader 引入
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env']
          }
        }
      },

      // css处理
      {
        test: /\.(css|styl)$/,
        // 解析顺序从右至左, style-loader 将css 注入到页面的header里
        // use: ['style-loader', 'css-loader', 'stylus-loader'],

        // 解析顺序从右至左, MiniCssExtractPlugin.loader实现 css 文件抽离
        use: [MiniCssExtractPlugin.loader, 'css-loader', 'stylus-loader']
      },

      // 图片资源
      {
        test: /\.(jpg|jpeg|gif|png)$/,
        use: {
          loader: 'url-loader',
          options: {
            limit: 7,
            name: imageName
          }
        }
      },

      // vue引入
      {
        test: /\.vue$/,
        use: {
          loader: 'vue-loader'
        }
      }
    ]
  },

  // plugin配置, webpack plugin 是一个类, plugins 填写的都是插件的实例
  plugins: [
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, '../public/index.html')
    }),

    new VueLoaderPlugin(),

    new MiniCssExtractPlugin({
      filename: ({ chunk }) => {
        return `${chunk.name.replace('js/', 'css/')}${cssName}.css`
      }
    })
  ]
}